import request from './request';
import storage from './storage';
import aop from './aop';
import { Message } from 'view-design';

/* eslint-disable */
import config from '../utils/config';
import ErrorToolTips from '../components/ErrorToolTips';

/** 保存用户信息 */
function saveUserInfo(userInfo, persistence = true) {
  storage.setAttributeToStorage('user_info', userInfo, persistence);
}

/** 获取当前登陆人信息 */
function getUserInfo(persistence = true) {
  return storage.getAttributeFromStorage('user_info', persistence);
}

/** 保存变量到window.sessionStorage或者window.localStorage */
function setAttributeToStorage(name, value, persistence = false) {
  storage.setAttributeToStorage(name, value, persistence);
}

/** 获取cookie */
function getCookie(name) {
  return storage.getCookie(name);
}

/** 从当前会话中获取变量 */
function getAttributeFromStorage(name, persistence = false) {
  const value = storage.getAttributeFromStorage(name, persistence);
  return value;
}

/** 从文件系统下载文件 */
async function downloadFileFromFileSystem(url,fileName) {
  const userInfo=getUserInfo()
  var newFileUrl=encodeURI(`${url}&jwt=${userInfo.jwt}`, "utf-8");
  const a = document.createElement('a');
  a.href = newFileUrl;
  a.download = fileName;
  a.style.display = 'none';
  document.body.appendChild(a);
  a.click();
  console.log(a)
  URL.revokeObjectURL(a.href);
  URL.revokeObjectURL()
  document.body.removeChild(a);
  // window.location.href=newFileUrl
}

/** 从本地存储中删除用户信息 */
function removeUserInfo() {
  storage.removeAttributeFromStorage('user_info');
  storage.removeAttributeFromStorage('user_info', true);
}

/** 登出 */
async function signOut() {
  const logout = config.serverProxy + config.authServicePath + '/logout';
  await getRequest(logout);
  removeUserInfo();
  window.vueRouter.push('/signin');
}

/** 判断用户是否已登录 */
function isAuthenticated() {
  const userInfo = getUserInfo();
  if (userInfo) {
    return true;
  } else {
    return false;
  }
}

/** 判断是否拥有权限 */
function hasPermission(permission) {
  if (!permission || permission === '')
    return true;
  else {
    /** 如果是调试模式 */
    /*if (config.env === 'dev') {
      return true;
    }*/
    return true;
    const userInfo = getUserInfo();
    if (!userInfo) {
      return false;
    } else {
      const permissions = userInfo.permissions;
      //如果传递进来的是数组
      if (permission instanceof Array) {
        for (let i = 0; i < permission.length; i++) {
          const permissiontemp = permission[i];
          for (let h = 0; h < permissions.length; h++) {
            if (permissiontemp === permissions[h]) {
              if (i === permission.length - 1) {
                return true;
              } else {
                break;
              }
            } else {
              if (h === permissions.length - 1) {
                return false;
              }
            }
          }
        }
      }
      //如果传递进来的是字符串
      else {
        for (let f = 0; f < permissions.length; f++) {
          if (permission === permissions[f]) {
            return true;
          } else {
            if (f === permissions.length - 1) {
              return false;
            }
          }
        }
      }
    }
  }
}

/** 判断是否拥有角色 */
function hasRole(role) {
  if (!role || role === '')
    return true;
  else {
    /** 如果是调试模式 */
    if (config.env === 'dev' || config.env === 'prod' || config.env ==='local') {
      return true;
    }
    return true;
    const userInfo = getUserInfo();
    if (!userInfo) {
      return false;
    } else {
      const roles = userInfo.roles;
      //如果传递进来的是数组
      if (role instanceof Array) {
        for (var i = 0; i < role.length; i++) {
          const roletemp = role[i];
          for (var h = 0; h < roles.length; h++) {
            if (roletemp === roles[h]) {
              if (i === role.length - 1) {
                return true;
              } else {
                break;
              }
            } else {
              if (h === roles.length - 1) {
                return false;
              }
            }
          }
        }
      }
      //如果传递进来的是字符串
      else {
        for (let h = 0; h < roles.length; h++) {
          if (role === roles[h]) {
            return true;
          } else {
            if (h === roles.length - 1) {
              return false;
            }
          }
        }
      }
    }
  }
}

function resultCheck(result) {
  result.then(response => {
    let isError = false;
    let errorMessage;
    let errorCode;
    if (response && response.status >= 200 && response.status < 300) {
      if (parseInt(response.data.errorCode) !== 0) {
        isError = true;
        errorMessage = response.data.msg;
        errorCode = response.data.errorCode;
      }
    } else {
      if(response){
        isError = true;
        errorMessage = response.statusText;
        errorCode = response.status;
      }
      console.log(response, 'response');
      errorMessage = response;
      // errorMessage = response.statusText;
      // errorCode = response.status;
    }
    if (response&&response.data.code === 0) {
      isError = false;
    }
    if (isError) {
      if (errorCode === 4401) {
        removeUserInfo();
        window.location.reload();
      } else {
        if (response.status !== 200) {
          Message.error({
            content: `${errorMessage}`
          })
        }
        Notice.error({
          duration: 6,
          title: `错误代码:${errorCode}`,
          desc: errorMessage,
          render: (h) => {
            return h(ErrorToolTips, {
              props: {
                data: {
                  errorCode,
                  errorMessage
                }
              }
            });
          }
        });
      }
    }
  });
}

/** 初始化请求时认证信息 */
function initRequestAuthInfo(config) {
  const userInfo = getUserInfo();
  if (!config) {
    config = {};
  }
  if (!config.headers) {
    config.headers = {};
  }
  if (userInfo) {
    config.headers['X-Request-ClientId'] = userInfo.clientId;
    config.headers['P-Authorization-test'] = 'P-Bearer '+ userInfo.token;
  }
  return config;
}

/** 发送http请求 */
function httpRequest(url, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.request(url, config);
  resultCheck(refsult);
  return refsult;
}

function getRequest(url, params, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.getRequest(url, params, config);
  resultCheck(refsult);
  return refsult;
}

function putRequest(url, data, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.putRequest(url, data, config);
  resultCheck(refsult);
  return refsult;
}

function postRequest(url, data, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.postRequest(url, data, config);
  resultCheck(refsult);
  return refsult;
}

function postRequestForm(url, data, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.postRequestForm(url, data, config);
  resultCheck(refsult);
  return refsult;
}

function deleteRequest(url, params, config) {
  config = initRequestAuthInfo(config);
  const refsult = request.deleteRequest(url, params, config);
  resultCheck(refsult);
  return refsult;
}

const webAppService = {
  /** 保存用户信息到本地存储 */
  saveUserInfo: saveUserInfo,
  /** 获取当前登陆人信息 */
  getUserInfo: getUserInfo,
  /** 从本地存储中删除用户信息 */
  removeUserInfo: removeUserInfo,
  /** 获取cookie */
  getCookie: getCookie,
  /** 发送http请求 */
  httpRequest: httpRequest,
  getRequest: getRequest,
  putRequest: putRequest,
  postRequest: postRequest,
  postRequestForm: postRequestForm,
  deleteRequest: deleteRequest,
  /** 判断是否拥有权限 */
  hasPermission: hasPermission,
  /** 判断是否拥有角色 */
  hasRole: hasRole,
  /** 判断用户是否已登录 */
  isAuthenticated: isAuthenticated,
  /** 保存变量到本窗口会话 */
  setAttributeToStorage: setAttributeToStorage,
  /** 从当前会话中获取变量 */
  getAttributeFromStorage: getAttributeFromStorage,
  signOut: signOut,
  downloadFileFromFileSystem:downloadFileFromFileSystem
};

function beforeRequest() {
  let url = arguments[0];
  url = `${url}`;
  /* eslint-disable */
  // if (url.indexOf('?') !== -1) {
  // url = `${url}&timestamp=${new Date().getTime()}`;
  // } else {
  // url = `${url}?timestamp=${new Date().getTime()}`;
  // }
  arguments[0] = url;
  return arguments;
}

aop.before(webAppService, 'getRequest', beforeRequest);
aop.before(webAppService, 'putRequest', beforeRequest);
aop.before(webAppService, 'postRequest', beforeRequest);
aop.before(webAppService, 'postRequestForm', postRequestForm);
aop.before(webAppService, 'deleteRequest', beforeRequest);

export default webAppService;
